package by.gusto.afisha.net;

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import by.gusto.afisha.model.Category;

public class GustoCategoryGrabber implements ICategoryGrabber, PageDownloader.IDownloadListener {

	private static final String PATTERN = "div class=\\\"bottom\"(.*?\\s)*?((<li><a href=\".*?\">.*?</a></li>)+)";
	private static final int BODY_INDEX = 2;
	
	private static final String CATEGORY_PATTERN = "<a href=\"(.*?)\">(.*?)</a>";
	private static final int URL_INDEX = 1;
	private static final int NAME_INDEX = 2;
	
	private String mBaseUrl = null;
	private IOnCompliteListener mListener = null;
	private SoftReference<ArrayList<Category>> mCache = null;
	
	public GustoCategoryGrabber(final String baseUrl) {
		mBaseUrl = baseUrl;
	}
	
	@Override
	public ArrayList<Category> getCategories() {
		if (mCache != null) {
			ArrayList<Category> result = mCache.get();
			if (result != null) {
				return result;
			}
		}
		
		if (mListener != null) {
			PageDownloader.getPage(mBaseUrl, this);
		}
		return null;
	}

	@Override
	public void setOnCompliteListener(final IOnCompliteListener listener) {
		mListener = listener;
	}

	@Override
	public void onComplite(final String page) {
		ArrayList<Category> result = new ArrayList<Category>();
		Pattern p = Pattern.compile(PATTERN);
		Matcher m = p.matcher(page);
		if (m.find()) {
			String content = m.group(BODY_INDEX);
			
			Pattern categoryPattern = Pattern.compile(CATEGORY_PATTERN);
			Matcher categoryMatcher = categoryPattern.matcher(content);
			
			while (categoryMatcher.find()) {
				Category category = new Category();
				category.name = categoryMatcher.group(NAME_INDEX);
				category.url = categoryMatcher.group(URL_INDEX);
				category.externalId = (category.name + ServerType.GUSTOBY.getId()).hashCode();
				
				result.add(category);
			}
		}
		if (mListener != null) {
			mListener.onComplite(result);
		}
		
		// cache result
		mCache = new SoftReference<ArrayList<Category>>(result);
		
		// save categories into local db
		Category.save(result, ServerType.GUSTOBY);
	}
}
